#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define THREADNUM 4

int g_tickets = 100;

pthread_mutex_t g_lock; //定义互斥锁变量为全局变量


void* GetTicketStart(void* arg)
{
    while(1)
    {
        //pos1---lock 
        //加锁
        pthread_mutex_lock(&g_lock);
        if(g_tickets > 0)
        {
            printf("i am %p, i have ticket %d\n",pthread_self(),g_tickets);
            //pos2---lock 在这里加锁没有作用
            g_tickets--;
        }
        else 
        {
            pthread_mutex_unlock(&g_lock);
            break;
        }
        //解锁
        pthread_mutex_unlock(&g_lock);
    }
    return NULL;
}

int main()
{
    pthread_mutex_init(&g_lock,NULL); //（动态）初始化互斥锁，后面需要销毁
    pthread_t tid[THREADNUM];
    for(int i=0;i<THREADNUM;i++)
    {
        int ret = pthread_create(&tid[i],NULL,GetTicketStart,NULL);
        if(ret < 0)
        {
            perror("pthread_create");
            return 0;
        }
    }
    for(int i=0;i<THREADNUM;i++)
    {
        pthread_join(tid[i],NULL); 
    }

    pthread_mutex_destroy(&g_lock);
    return 0; 
}
